<template>
  <div>
    <div class="popover1">
      <input
        type="text"
        :placeholder="$t('public.pleaseEnter')"
        class="popover1_inpit"
        v-model.trim="nameSearch"
        v-on:keyup="searchTree"
      />
      <div class="prompt" v-show="popoLoading">{{ $t('webchat.loading') }}</div>
      <ul class="tree" v-show="onlineAgentsInvite.length && popoLoading === false">
        <li class="transfer_li_box" v-for="(model, index) in onlineAgentsInvite" :key="model._id">
          <div class="box1">
            <div
              :class="get(model, 'AssignMembers.length') ? '' : 'subpadding'"
              class="transfer_li transfer_group clearBoth"
              @click.stop="setOpen(model)"
              :index="index"
            >
              <span class="open-close-icon" v-show="get(model, 'AssignMembers.length')"
                ><i :class="model.open ? 'el-icon-minus' : 'el-icon-plus'"></i
              ></span>
              <span
                v-show="get(model, 'AssignMembers.length') > 0"
                class="transfer_li_title cata-name ellipsis"
                v-html="
                  model.highlightCtx
                    ? `${model.highlightCtx}(${get(model, 'AssignMembers.length')}${$t('webchat.onlineNum')})`
                    : `${model.DisplayName}(${get(model, 'AssignMembers.length')}${$t('webchat.onlineNum')})`
                "
                :title="model.DisplayName + '(' + get(model, 'AssignMembers.length') + $t('webchat.onlineNum') + ')'"
              ></span>
              <span class="agent-line" v-if="!model.AssignMembers">{{ model.displayName }}</span>
              <span v-if="model.maxChatNum" :class="['transfer-chat-maxChat', getChatMaxChatClass(model)]"
                >（{{ `${model.chatNum}/${model.maxChatNum}` }}）</span
              >
              <span
                class="transfer_btn iconfont icon-zhuanjie1 transfer_group_btn"
                @click.stop="onShow(model, true)"
              ></span>
            </div>
          </div>
          <ul
            v-show="model.open && get(model, 'AssignMembers.length')"
            class="transfer_li_ul"
          >
            <li
              class="quickReSys transfer_li clearBoth"
              v-for="modelagent in model.AssignMembers"
              :key="modelagent._id"
            >
              <span
                class="cata-name ellipsis"
                @click.stop="onShow(model, false, modelagent)"
                :title="modelagent.displayName"
                v-html="modelagent.highlightCtx ? modelagent.highlightCtx : modelagent.displayName"
              ></span>
              <span v-if="modelagent.maxChatNum" :class="['chatNum', getChatMaxChatClass(modelagent)]"
                >（{{ modelagent.chatNum }}/{{ modelagent.maxChatNum }}）</span
              >
              <span
                class="transfer_btn iconfont icon-zhuanjie1 transfer_group_btn"
                @click.stop="onShow(model, false, modelagent)"
              ></span>
            </li>
          </ul>
        </li>
      </ul>
      <div class="prompt" v-show="!onlineAgentsInvite.length && popoLoading === false">{{ $t('webchat.noData') }}</div>
    </div>
    <webchatTransferRemark :visible="visible" :on-cancel="onCancel" :on-ok="onOk" />
  </div>
</template>
<script type="text/javascript">
import { deepClone } from '../../../utils/m7Utils'
import { flattenDeep, uniqBy, get, pick, isEmpty, random, throttle } from 'lodash'
import { filterXSS } from '@/utils/m7Utils'
import webchatTransferRemark from './webchatTransferRemark.vue'
import {ACCEPT, REFUSE} from './webchatTransferNotice.vue'
import bus from '@/store/eventBus'
const TRANSFER_REQUEST = 'request'
const TRANSFER_CANCEL = 'cancel'
export default {
  components: {
    webchatTransferRemark
  },
  data() {
    return {
      nameSearch: '',
      get,
      visible: false,
      transferData: {},
      transferConfig: {},
      remark: '',
      isTransferRequest: null,
      transferSkillGroup: false,
      transferAgent: {}
    }
  },
  props: {
    transferVisible: {
      type: Boolean,
      default: false
    },
    AssignTreeData: {
      type: Array,
      default: function () {
        return []
      }
    },
    webchatData: {
      type: Object,
      default: () => ({})
    },
    onlineAgentsInvite: {
      type: Array,
      default: function () {
        return []
      }
    },
    popoLoading: {
      type: Boolean,
      default: function () {
        return false
      }
    }
  },
  computed: {
    keywords() {
      return this.nameSearch.trim()
    },
    transferMessage() {
      // console.log('***2***', this.$store.state.webchat.transferNotice)
      return this.$store.state.transferNotice || this.$store.state.transferNoConfirmNotice
    },
    showTransfer() {
      return Object.keys(this.transferMessage).length
    },
    transferConfirmParam() {
      if (typeof this.isTransferRequest !== 'boolean') {
        return ''
      }
      return this.isTransferRequest ? TRANSFER_REQUEST : TRANSFER_CANCEL
    },
    openRemark() {
      return this.transferConfig.redirectWebchatSessionCommentFlag
    },
    agentId() {
      return this.$store.state.session.user._id
    }
  },
  watch: {
    transferMessage: {
      handler(newVal) {
        if (!isEmpty(newVal)) {
          if (newVal.redirectResponse === ACCEPT) {
            this.$store.commit('BLANK', 'webchat_todo')
            this.$router.replace({path: '/index/webchat/webchat_todo'})
          }
          if (newVal.redirectResponse === REFUSE) {
            this.updateChannel(newVal)
          }
        }
      },
      immediate: true,
      deep: true
    },
    transferVisible: {
      handler() {
        this.getConfig()
      },
      immediate: true,
    }
  },
  mounted() {
    console.log(this.$store)
    bus.$on('initTransferRequest', this.initTransferRequest)
  },
  beforeDestroy() {
    bus.$off('initTransferRequest', this.initTransferRequest)
  },
  methods: {
    getChannelId (channel) {
      return get(channel, 'redirectData._id') || channel._id || channel.chatSessionId
    },
    updateChannel(channel) {
      this.$store.commit('webchat/UPDATE_WEBCHAT_TODO', {
        channelId: this.getChannelId(channel),
        key: 'redirectToUser',
        val: null
      })
    },
    getConfig: throttle(async function() {
      const res = await this.$store.dispatch('getDicByType', { type: 'redirectWebchatSessionCofing' })
      this.transferConfig = res.row || {}
    }, 500),
    onCancel() {
      this.visible = false
    },
    onShow(model, transferSkillGroup, transferAgent) {
      this.transferSkillGroup = transferSkillGroup
      this.transferAgent = transferAgent
      this.transferData = model
      if (this.openRemark) {
        this.visible = true
      } else {
        this.transfer(
          model, 
          transferSkillGroup ? 'transferGroup' : '', 
          transferAgent
        )
      }
    },
    async onOk(remark) {
      if (!remark.trim()) {
        return this.$message.error('备注内容不能为空')
      }
      this.remark = remark
      const params = {
        accessId: this.webchatData.accessId,
        sid: this.webchatData.sid,
        _id: this.webchatData._id,
        content: remark
      }
      await this.$store.dispatch('updateWebchatSessionRemark', params)
      this.transfer(
        this.transferData, 
        this.transferSkillGroup ? 'transferGroup' : '', 
        !isEmpty(this.transferAgent) ? this.transferAgent : {}
      )
      this.onCancel()
    },
    getChatMaxChatClass(item) {
      return +item.maxChatNum <= +item.chatNum ? 'danger' : ''
    },
    searchTree() {
      const data = []
      this.AssignTreeData.forEach((item) => {
        let obj = deepClone(item)
        let dataLi = {
          AssignMembers: []
        }
        let growName = obj.DisplayName
        let growIdexOf = growName.indexOf(this.keywords)
        let oneHit = false
        if (obj.AssignMembers.length) {
          for (let i = 0; i < obj.AssignMembers.length; i++) {
            const { data, isHit } = this.makeTransfer(obj.AssignMembers[i], { keywords: this.keywords })
            this.$set(obj, `AssignMembers[${i}]`, data)
            if (isHit) {
              oneHit = true
            }
            dataLi.AssignMembers.push(obj.AssignMembers[i])
          }
          if (growIdexOf !== -1) {
            oneHit && this.$set(obj, 'open', true)
            data.push(obj)
            if (!dataLi.AssignMembers.length) {
              return
            }
            obj.AssignMembers = dataLi.AssignMembers
          } else {
            if(oneHit) {
              this.$set(obj, 'open', true)
              data.push(obj)
            }
          }
        }
      })
      this.$emit('searchTree', this.nameSearch, data)
      this.$nextTick(this.setSkillGroupHighlight)
    },
    setSkillGroupHighlight() {
      this.onlineAgentsInvite.forEach((item) => {
        const { data: res } = this.makeTransfer(item, { keywords: this.keywords, nameKey: 'DisplayName' })
        this.$set(item, 'highlightCtx', this.keywords ? res.highlightCtx : null)
      })
      this.$forceUpdate()
    },
    makeTransfer(obj, options) {
      const { nameKey, highlightKey, keywords } = {
        nameKey: 'displayName',
        highlightKey: 'highlightCtx',
        keywords: '',
        ...options
      }
      if (obj[highlightKey]) {
        obj[highlightKey] = this.getOriginCtx(obj[highlightKey])
      }
      const isHit = obj[nameKey].includes(keywords)
      if (isHit) {
        obj[highlightKey] = this.getTransferCtx(obj[nameKey], keywords)
      }
      return {
        isHit,
        data: obj
      }
    },
    getTransferCtx(ctx, keywords) {
      if (!keywords.trim()) {
        return ctx
      }
      return filterXSS(ctx.split(keywords).join(`<span class="webChat-transfer-highlight">${keywords}<span>`))
    },
    getOriginCtx(ctx) {
      const p = document.createElement('p')
      p.innerHTML = ctx
      return p.innerText
    },
    openSearch(data) {
      if (!this.nameSearch) {
        data = data.filter((i) => i.AssignMembers)
      } else {
        data.push(...uniqBy(flattenDeep(data.map((i) => i.AssignMembers)), '_id'))
      }
    },
    setOpen(model) {
      if (!model) {
        return
      }
      this.$set(model, 'open', !Boolean(model.open))
    },
    getTransferData (model, isSkillGroup) {
      const transferConfig = pick(
        this.transferConfig, 
        [
          'redirectWebchatSessionCommentFlag', 
          'redirectWebchatSessionComment',
          'redirectWebchatSessionConfirmFlag',
          'redirectWebchatSessionNotQueueFlag'
        ]
      )
      const { AssignMembers = [] } = model || {}
      console.log('***agentId***', this.agentId, AssignMembers)
      const filterMember = AssignMembers.filter(i => get(i, '_id') !== this.agentId)
      const randomAgent = filterMember[random(filterMember.length - 1)]
      const randomAgentId = isSkillGroup ? randomAgent._id : ''
      return {
        ...transferConfig,
        ...(this.openRemark ? {redirectWebchatSessionComment: this.remark} : {}),
        ...(randomAgentId ? {redirectConfirmQueueAgent: randomAgentId} : {})
      }
    },
    initTransferRequest() {
      this.isTransferRequest = null
    },
    transfer(model, type, modelagent) {
      console.log(model, type, modelagent)
      const isSkillGroup = isEmpty(modelagent)
      this.isTransferRequest = true
      this.$nextTick(() => {
        const data = this.getTransferData(model, isSkillGroup)
        this.$emit('transfer', {
          model,
          type,
          modelagent,
          transfer: data
        })
      })
    }
  }
}
</script>
<style lang="stylus">
.webChat-transfer-highlight
  color rgba(0, 0, 255, .6)
  span
    color #000
</style>
<style lang="stylus" scoped>
@import "./style/webchatCon.styl"
.danger
  color red
.transfer_group
  text-overflow ellipsis
  overflow hidden
  white-space nowrap
.agent-line
  margin-left 10px
.open-close-icon
  position absolute
  left 0
  top 3px
.transfer_li_ul
  position relative
.transfer_li
  padding-left 12px
  position relative
  color #000!important
  .cata-name
    display inline-block
    width calc(100% - 70px)
  .transfer-chat-maxChat,.chatNum
    display inline-block
    width 70px
    vertical-align top
    position absolute
    right 10px
    top 2px
</style>
